﻿/*
创建人：longb
日期：2022-07-12
描述：自动排产js
*/
var page = {
    pagetotal: 0,
    pageSize: 20,//yuxj20230223
    pageNumber: 1,
    ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ZSLimitedCapacityHandler.ashx",
    //初始化页面
    init: function () {
        page.bind();
//        customizedEasyuiPagination('pp'); //定制化分页
        NewcustomizedEasyuiPagination('pp'); //定制化分页
        $('#pp').find('.pageSize').val(page.pageSize); //初始化行数
        //page.GetApsOrderBill();
    },
    //页面事件绑定
    bind: function () {
        $('#OrderType').combobox({
            data: [{ id: 1, text: '正常' }, { id: 0, text: '临时'}],
            valueField: 'id',
            textField: 'text'
        });
        $('#BigSmall').combobox({
            data: [{ id: 0, text: '否' }, { id: 1, text: '是'}],
            valueField: 'id',
            textField: 'text'
        });
        $('#OrderType').combobox('setValue', 1);
        $('#BigSmall').combobox('setValue', 1);
        //排产池单信息
        $("#gdApsPool").datagrid({
            rownumbers: true,
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
//                customizedEasyuiPagination('pp'); //定制化分页
                NewcustomizedEasyuiPagination('pp'); //定制化分页
            },
            columns: [[
                { field: 'ck', title: '选择', checkbox: true },
                 { field: 'ENGINENO', title: '发动机号', width: 120 },
                 { field: 'MFGORDERNAME', title: '订单号', width: 150 },
		         { field: 'CONTAINERNO', title: '任务单号', width: 180 },
		         { field: 'WORKFLOWTYPE', title: '任务类型', width: 80 }, //--
                 { field: 'PRODUCTNAME', title: '件号', width: 100 },
                 { field: 'PRODUCTDESCRIPTION', title: '件号名称', width: 90 },
                 { field: 'WFR', title: '工艺信息', width: 150 },
                 { field: 'WFDESC', title: '工艺名称', width: 120 },
                 { field: 'PLANNEDSTARTDATE', title: '计划开始时间', width: 130, formatter: function (value, row, index) {
                     if (value != null)
                         return dayjs(value).format("YYYY-MM-DD");
                 }
                 },
                 { field: 'PLANNEDFINISHDATE', title: '计划完成时间', width: 130, formatter: function (value, row, index) {
                     if (value != null)
                         return dayjs(value).format("YYYY-MM-DD");
                 }
                 },
                 { field: 'WORKFLOWSTEPNAME', title: '阶段', width: 100 }
	           ]],
               onCheck: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
            onUncheck: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
            onCheckAll: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
            onUncheckAll: function (index, rowData) {
                page.reset(false, false, true);
                page.searchContainerAps();
            },
        });
        $("#gdContainerAps").datagrid({
            groupField: 'CONTAINERNAME',
            view:groupview,
            groupFormatter: function (value, rows) {
                var val = value + ' - ' + '已排 ' + rows.length + ' 种策略'
                return val; //"<span data-count=" + rows.length + " class='customTitle' >" + val + "</span>";
            },
            columns: [[
                 { field: 'STARTTIME', title: '开始时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 },
                     styler: function (value, row, index) {
                         if (value != null && dayjs(dayjs(value).format('YYYY-MM-DD')) < dayjs(dayjs(row.MFGSTARTDATE).format('YYYY-MM-DD'))) {//REALSTARTDATE
                             return 'background-color:#ffee00;';
                         }
                     }
                 },
                 { field: 'ENDTIME', title: '结束时间', width: 125, formatter: function (value, row, index) {
                     if (value != null)
                         return value.substring(0, value.lastIndexOf(":"));
                 },
                     styler: function (value, row, index) {
                         if (value != null && dayjs(dayjs(value).format('YYYY-MM-DD')) > dayjs(dayjs(row.MFGENDDDATE).format('YYYY-MM-DD'))) {
                             return 'background-color:#ffee00;';
                         }
                     }
                 },
                 { field: 'APSTYPE', title: '排产策略', width: 80, formatter: function (value, row, index) {
                     return value.indexOf('5')>0?"正排":(value.indexOf('4')>0?"倒排":"");
                 }
                 },
                 {field: 'STATUS', title: '排产状态', width: 80},
                 { field: 'OPERATE', title: '操作', width: 150, formatter: function (value, row, index) {
                     var para = {
                         CONTAINERID: row.CONTAINERID,
                         WORKFLOWID: row.WORKFLOWID,
                         APSPLANINFOID: row.APSPLANINFOID
                     }
                     var btnHtml = "<button   class='' onclick=page.viewGanttAndSave('"+row.APSTYPE+"',false) style='cursor:pointer;width: 40px; height: 22px'>查看</button>";
                     btnHtml += "<button title='查看此批次排产的策略对比甘特图'  class='' onclick=page.viewGanttAndSave('',true) style='cursor:pointer;margin-left:10px;width: 80px; height: 22px'>策略对比</button>";
                     return btnHtml
                 }
                 }
	           ]]
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
//                customizedEasyuiPagination('pp'); //定制化分页
                NewcustomizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.GetApsOrderBill();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.pageSize=$('#pp').find('.pageSize').val() == "" ? page.pageSize : Number($('#pp').find('.pageSize').val());
            page.GetApsOrderBill();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true,true);
        });
    },
    TypeChange:function(){
       var opt=$("input:radio[name='Level_1']:checked").val()
       if(opt==null){
            $('#Level2').radiobutton({checked:false});
            $('#Level3').radiobutton({checked:false});
       }
       else if(opt=="0"){
            $('#Level2').radiobutton({checked:true,disabled:false});
            $('#Level3').radiobutton({disabled:true});
       }
       else
       {
            $('#Level3').radiobutton({checked:true,disabled:false});
            $('#Level2').radiobutton({disabled:true});
       }
       var opt1=$("input:radio[name='Level_2']:checked").val()
         if(opt1=="2"){
            $('#Level6').radiobutton({checked:true,disabled:false});
            //$('#Level7').radiobutton({disabled:true});
       }else{
            $('#Level7').radiobutton({checked:true,disabled:false});
            //$('#Level6').radiobutton({disabled:true});
       }
       //var opt2=$("input:radio[name='Level_2']:checked").val()
       //var opt3=$("input:radio[name='Level_3']:checked").val()
      
    },
    //查询
    searchData: function () {
        page.reset(false,true,true);
        page.pageNumber = 1;
        page.GetApsOrderBill();
    },
    //查询任务单信息
    GetApsOrderBill: function () {
        var frdata = $('#searchForm').serializeArray();
        var data = {};
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var param = {
            action: "GetZsApsOrderTask",
            IsPool:'1',
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            data: JSON.stringify([data])
        };
        page.post(param, function (res) {
            if (res.Result) {
                page.pagetotal = res.RowCount;
                $('#gdApsPool').datagrid('loadData', res.DBTable);
            }
        });
    },
    //添加排产池
    addApsPool: function () {
        var url = "ZSApsOrderSelect.html?v=" + new Date().getTime();
        url += "&parentDiv=orderSelect";
        $('#orderSelect').dialog({
            title: '选择任务单到排产池',
            top: 10,
            closed: false,
            cache: false,
            width: "95%",
            height:"100%",
            content: '<iframe src="' + url + '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>',
            returnData: null,
            popupData: '', //弹出页面的传参
            onClose: function () {
                var returnData = $("#orderSelect").dialog('options').returnData; //返回数据
                if (returnData != null) {
                    page.searchData();
                    displayMessage("添加成功", true);
                }
            }
        });
    },
    //移除排产池
    removeApsPool: function () {
        var rows = $('#gdApsPool').datagrid('getChecked');
        if (rows.length == 0) {
            displayMessage("请先勾选任务单信息，再进行操作");
            return;
        }
       var param = {
            action: "removeApsPool",
            data: JSON.stringify(rows)
        };
        page.post(param, function (res) {
            if (res.Result) { page.GetApsOrderBill(); }
            displayMessage(res.Message, res.Result);
        });
     },
    //Aps排产计算
    apsLmCalculate: function () {
     var Level_1=$("input:radio[name='Level_1']:checked").val();
     var Level_2=$("input:radio[name='Level_2']:checked").val();
     var Level_3=$("input:radio[name='Level_3']:checked").val();
     var Level_4=$("input:radio[name='Level_4']:checked").val();
     var rows = $('#gdApsPool').datagrid('getChecked');
        if (rows.length == 0) {
            displayMessage("请先勾选任务单信息，再进行排产");
            return;
        }
     if(Level_1==undefined){ displayMessage("请选择Ⅰ级排产策略，再进行操作"); return;}
     if(Level_3==undefined){ displayMessage("请选择Ⅲ级排产策略，再进行操作"); return;}
      var param = {
            action: "apsLmCalculate",
            data: JSON.stringify(rows),
            policy1:Level_1,
            policy2:Level_2,
            policy3:Level_3,
            policy4:Level_4
        };
        page.post(param, function (res) {
            if (res.Result) { page.GetApsOrderBill(); }
            displayMessage(res.Message, res.Result);
        });
    },
    //
    searchContainerAps: function () {
        var rowDatas = $("#gdApsPool").datagrid("getChecked");
        if (rowDatas.length == 0) {
            return;
        }
        var containerPara = [];
        rowDatas.forEach(
          function (item) {
              containerPara.push({
                  containerId: item.CONTAINERID,
                  workflowId: item.WORKFLOWID
              });
          }
        );

        var param = {
            action: "getContainerLMAps",
            containers: JSON.stringify(containerPara)
        };

       page.post(param, function (res) {
            if (res.Result) { 
                var dt = res.DBTable;
                $("#gdContainerAps").datagrid('loadData', { total: dt.length, rows: dt });
             }
            displayMessage(res.Message, res.Result);
        });
     },
     //查看甘特图
    viewGanttAndSave: function (apsType,isCompare) {
       var param = [];
       var rows = $('#gdApsPool').datagrid('getChecked');
        if (rows.length == 0) {
            displayMessage("请先勾选任务单信息，再查看排产结果");
            return;
        }
       $.each(rows,function(index,item){
            param.push(item.CONTAINERID);
       });
       
        var url = "/InSiteWebApplication/forms/Custom/Zs/ZSApsGanttViewPage.html?v=" + new Date().getTime();
        url += "&parentDiv=dg" + "&isCompare=" + isCompare+"&apsType="+apsType;
        $('#dg').dialog({
            title: '工序计划甘特图',
            fit: true,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            popupData: param.join(','), //弹出页面的传参
            returnData: null,
            onClose: function () {
                page.searchContainerAps();
            }
        });
    },
    //查询重置
    searchReset: function () {
        page.reset(true,true,true);
//        $('#searchForm').form('clear');
//        page.bind();
    },

    //清除方法，重要！！！
       reset: function (iscondition, isresult, isDetail) {
        clearMessage();
        if (iscondition) {
            $("#txtMfgorderName").textbox("setValue", ""); //订单号
            $("#txtProduct").textbox("setValue", ""); //件号
            $("#txtContainer").textbox("setValue", ""); //任务单
            $("#txtPlanStartTime").textbox("setValue", ""); //排产开始时间
            $("#txtPlanEndTime").textbox("setValue", ""); //排产结束时间
            $("#OrderType").textbox("setValue", ""); //任务单类型
            $("#BigSmall").combobox("setValue", ""); //大小件          
        }

        if (isresult) {
            clearEasyuiDataGrid("gdApsPool", 1); //查询结果列表
            $('#EditorForm').form('clear');
            page.pageNumber = 1; page.pagetotal = 0;//重置分页
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        }
        if(isDetail)
        {
            clearEasyuiDataGrid("gdContainerAps", 1); //明细信息
        }
    },
    //post数据
    post: function (param, callback) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    }
}
$(function () {
    page.init();
});